# coding=utf-8
"""
Created on 2018年09月04日
"""
from util_base.ufo_decorators import processor
from common_base.cmd import CMD
from processor_base.base_processor import BaseProcessor
from util_base import common_utils
from util import formula
from setting_base.setting import C


@processor(CMD.CMD_FOY_YOU_ARTICLES_SCORE, internal_access=True)
class ForYouArticlesScore(BaseProcessor):
    """
    脚本 ForYouArticlesScore
    """
    
    TAG = 'ForYouArticlesScore'
    
    def __init__(self, handler):
        """
        Constructor
        """
        BaseProcessor.__init__(self, handler)
        self.article_data_limit = C('ALIVE_SCRIPT_DATA_LIMIT')['FOR_YOU_ARTICLE_SCORE']

    def process(self):
        """
        process protocol
        """
        # 删除top=0的帖子分数(top=1的为运营指定的置顶帖子)
        self.alive_cmsdb.delete_for_you_article_score()

        # 获取top=1的帖子
        db_top_articles = self.alive_cmsdb.get_for_you_top_articles()
        top_article_ids = [e['article_id'] for e in db_top_articles]

        # 查询7天以内的帖子
        start_time_timestamp = self.NTIME - int(self.article_data_limit) * 24 * 3600
        start_time = common_utils.time_stamp_to_utc_time(start_time_timestamp)

        i = 0
        page_size = 1000
        while True:
            start = i * page_size
            article_list = self.alive_cmsdb.get_article_list_by_time(start_time, start, page_size)
            if not article_list:
                break

            # 计算分数
            self.count_score(article_list, top_article_ids)

            i += 1

        return dict()

    def count_score(self, article_list, top_article_ids):
        """
        按公式计算分数
        """
        article_score_list = list()
        for each_article in article_list:
            # articleId, commentCount, likeCount, shareCount, cvCount
            article_id = each_article['articleId']
            if article_id in top_article_ids:
                continue

            regDate = each_article['regDate']
            comment_count = each_article.get('commentCount', 0)
            like_count = each_article.get('likeCount', 0)
            share_count = each_article.get('shareCount', 0)
            cv_count = each_article.get('cvCount', 0)
            # 计算分数
            score = formula.for_you_article_score(cv_count, like_count, share_count, comment_count, regDate)

            article_score_list.append((article_id, score))

        self.alive_cmsdb.bach_save_for_you_article_score(article_score_list)

    def _verify_params(self):
        """
        重写父类方法, 作参数校验
        """
